$(document).ready(function() {
	//	cria o componente modal
//	$("#modalPopup").dialog({autoOpen:false, closeOnEscape: true, resizable:false, heigth: 140, modal: true});

	$("#loader").html("<div id='progressbar'></div><span id='mensagem_progressbar'></span>");
	
	$("#loader").css({visibility: 'visible', display: 'block'});
	
	$( "#progressbar" ).progressbar({value: 0});
	
	$("html").block({  message: $("#loader"), 
									css: { 'border': '0px',
										'background': 'transparent',
										'color': 'white',
										'font-family': 'Verdana,Arial,Helvetica,sans-serif',
									    'font-weight': 'normal'
									},
									overlayCSS:  { 
								        backgroundColor: '#000', 
								        opacity:         0.89 
								    } 
	  						});
	  						
	$("#mensagem_progressbar").html("Iniciando sistema...");
	$("#mensagem_progressbar").html("Buscando bibliotecas javascript...");
	
	
	loadJs();

	
});


var enderecoJs = new Array(); 
//enderecoJs.push('http://www.google.com/recaptcha/api/js/recaptcha_ajax.js');
enderecoJs.push('js/google/recaptcha_ajax.js');
enderecoJs.push('js/simpleautocomplete/simpleAutoComplete.js');
enderecoJs.push('js/jquery-json/jquery.json-2.2.min.js');   
enderecoJs.push('js/jupiterjs/jquery.formparams.min.js');   
enderecoJs.push('js/datatables/jquery.dataTables.min.js');    
enderecoJs.push('js/datatables/jQuery.fn.dataTableExt.oApi.fnSetFilteringDelay.js');    
enderecoJs.push('js/datatables/ColReorder.min.js');    
enderecoJs.push('js/datatables/ColReorderWithResize.js');    
enderecoJs.push('js/datatables/ColVis.min.js');    
enderecoJs.push('js/datatables/TableTools.min.js');    
//enderecoJs.push('js/datatables/jquery.dataTables.columnFilter.js');    ----------> incompativel com outros
enderecoJs.push('js/datatables/dataTables.scroller.js');
enderecoJs.push('js/keyframesandcode/jquery.populate.min.js');  
enderecoJs.push('js/keyframesandcode/jquery.highlight.js');  
enderecoJs.push('js/validationEngine/jquery.validationEngine-pt_BR.js');
enderecoJs.push('js/validationEngine/jquery.validationEngine.js');  
enderecoJs.push('js/digitalbush/jquery.maskedinput-1.3.min.js'); 
enderecoJs.push('js/jquerypriceformat/jquery.price_format.1.5.js'); 
enderecoJs.push('js/highcharts/highcharts.js'); 
enderecoJs.push('js/highcharts/modules/exporting.js'); 
enderecoJs.push('js/trentrichardson/jquery-ui-timepicker-addon.js'); 
enderecoJs.push('js/jqueryui/jquery-ui-i18n.min.js'); 
enderecoJs.push('js/shuber/jquery.favicons.min.js');  
enderecoJs.push('js/qTip/jquery.qtip-1.0.0-rc3.js');
enderecoJs.push('js/bbq/bbq.js'); 
enderecoJs.push('js/form/jquery.form.js');
enderecoJs.push('js/validate/jquery.validate.js'); 
enderecoJs.push('js/wizard/jquery.form.wizard.js'); 
enderecoJs.push('js/jboesch-Gritter/jquery.gritter.js'); 
enderecoJs.push('js/netsolhost/urlEncode.js');	
enderecoJs.push('js/phstc/jquery.dateFormat-1.0.js');
enderecoJs.push('js/springJson/json2.js');
//FRAMEWORK
enderecoJs.push('tela/inicio/meusUtils.js');
enderecoJs.push('tela/inicio/meusValidadores.js');
enderecoJs.push('tela/inicio/meusTooltip.js');
enderecoJs.push('tela/inicio/meusDatepicker.js');
enderecoJs.push('tela/inicio/meusPopups.js');
//a partir daqui a ordem importa
enderecoJs.push('tela/inicio/meusGerenciamentoDeErro.js'); //depende do meusPopups.js
enderecoJs.push('tela/inicio/meusCombobox.js');					//depende do meusPopups.js
enderecoJs.push('tela/inicio/meusLoadPage.js'); 					//depende do meusPopups.js		meusGerenciamentoDeErros.js
enderecoJs.push('tela/inicio/meusUtilsDatatables.js');
enderecoJs.push('tela/inicio/meusCRUD.js');							//depende do meusPopups.js		meusGerenciamentoDeErros.js		meusUtilsDatatables.js
enderecoJs.push('tela/inicio/meusWizard.js');						//depende do meusPopups.js		meusGerenciamentoDeErros.js		meusUtilsCRUD.js
enderecoJs.push('tela/inicio/meusDatatables.js');					//


var enderecoComboBox = 	new Array();
	enderecoComboBox.push('paises/combo/nome?class=br.com.educa.modelo.publico.Pais');
	enderecoComboBox.push('estadoes/combo/uf?class=br.com.educa.modelo.publico.Estado');
	//enderecoComboBox.push('ramosegurancapublicas/combo/nome?class=br.com.educa.modelo.publico.RamoSegurancaPublica');
	//enderecoComboBox.push('linguas/combo/nome?class=br.com.educa.modelo.publico.Lingua');
	//enderecoComboBox.push('bancoes/combo/nome/numero?class=br.com.educa.modelo.publico.Banco');
	//enderecoComboBox.push('departamentoproponentes/combo/nome?class=br.com.educa.modelo.instituicao.DepartamentoProponente');

	var totalEnderecoComboBox = enderecoComboBox.length;
	var totalEnderecoJs = enderecoJs.length;


	function loadDataSource(url,dataSource){
		jQuery.ajax({
			"type": "GET",
			"url": url,
			"contentType": "application/json",
			"dataType": "json",
		  	error: trataErro,
			success: function(data){
				dataSource.push(data);
			}
		});
	}



		
function loadJs(){
		var caminho = enderecoJs.shift();
		var progressao = 30 / totalEnderecoJs;
		$.ajax({
			url: caminho, dataType: "script", cache: false, //TODO cache desabilidado somente para desenvolvimento, voltar para true ao colocar em produção
		complete: function () {
			if(enderecoJs.length > 0){
		    	$("#mensagem_progressbar").html("Carregando "+caminho+" -> lib");
		    	var valAtual = $( "#progressbar" ).progressbar( "value");
		  		$( "#progressbar" ).progressbar( "option", "value", valAtual+progressao);
		  		loadJs();
			}else{
		  		loadDataSources();
			}				
		}
	});
} 

function loadDataSources(){
		var caminhoCombo = enderecoComboBox.shift();
		var progressao = 30 / totalEnderecoComboBox;
		$.ajax({
			url: caminhoCombo,"type": "GET", "contentType": "application/json", dataType: "json",error: trataErro,
			success: function (data) {
					var temp = caminhoCombo.split(".")[caminhoCombo.split(".").length-1];
					var dataSourceName = temp.charAt(0).toLowerCase() + temp.substring(1,temp.length) +"DataSource";
					eval(dataSourceName+"=data");
					$("#mensagem_progressbar").html("Carregando "+caminhoCombo+" -> lib");
			  		var valAtual = $( "#progressbar" ).progressbar( "value");
			  		$( "#progressbar" ).progressbar( "option", "value", valAtual+progressao);
		  		if(enderecoComboBox.length > 0 ){
			  		loadDataSources();
				}else{
					$("#mensagem_progressbar").html("Carregando sistema...");
					  $("#bg-topo").load("cabecalho",function() {
						  $("#mensagem_progressbar").html("Carregando cabeçalho...");
						  $( "#progressbar" ).progressbar( "option", "value", 68 );
						  $("#bg-rodape").load("rodape",function() {
							  $("#mensagem_progressbar").html("Carregando rodapé...");
							  $( "#progressbar" ).progressbar( "option", "value", 76 );
							  if($("#box_esquerda").size()!=0){
								  $("#box_esquerda").load("menus/seu",function() {
									  $("#mensagem_progressbar").html("Carregando o menu correspondente ao seu perfil...");
									  $( "#progressbar" ).progressbar( "option", "value", 84 );
									  loadPage("noticia", "noticia", "Notícias", false);
//									  $("#box_direita").load("noticia",function() {
//										  $("#mensagem_progressbar").html("Carregando avisos do sistema...");
//										  $( "#progressbar" ).progressbar( "option", "value", 92 );
//										  $("#mensagem_progressbar").html("Sistema pronto para uso <br /> Bem vindo!");
//										  $( "#progressbar" ).progressbar( "option", "value", 100 );
//										  setTimeout('$("html").unblock();', 900);
//										  $("#loader").css({visibility: 'hidden', display: 'none'});
//										  $("#loader").html("");
//										});
									  $("#mensagem_progressbar").html("Carregando avisos do sistema...");
									  $( "#progressbar" ).progressbar( "option", "value", 92 );
									  $("#mensagem_progressbar").html("Sistema pronto para uso <br /> Bem vindo!");
									  $( "#progressbar" ).progressbar( "option", "value", 100 );
									  setTimeout('$("html").unblock();', 900);
									  $("#loader").css({visibility: 'hidden', display: 'none'});
									  $("#loader").html("");
									});
							  }else{
									  $( "#progressbar" ).progressbar( "option", "value", 84 );
									  $("#box_direita").load("pesquisarCPF",function() {
										  $("#mensagem_progressbar").html("Carregando cadastro de currículo...");
										  $( "#progressbar" ).progressbar( "option", "value", 92 );
										  $("#mensagem_progressbar").html("Sistema pronto para uso <br /> Bem vindo!");
										  $( "#progressbar" ).progressbar( "option", "value", 100 );
										  setTimeout('$("html").unblock();', 900);
										  $("#loader").css({visibility: 'hidden', display: 'none'});
										  $("#loader").html("");
										});
							  }
							});
						});					
				}				
			}
		});
	} 

function loadAlerta(){
	jQuery.ajax({
		"type": "GET",
		"url": "despachosolicitacaos?find=ByUsuarioDestinatarioOuPerfil",
		"contentType": "application/json; charset=utf-8",
		"dataType": "json",
	  	error: trataErro,
	  	beforeSend: function(){
	  		$.gritter.removeAll();
	  	},
		success: function(data){
			for(var q=0; q<data.length; q++){
				var despachoSolicitacao = data[q];
				window.setTimeout(function(){addAlert(despachoSolicitacao); despachoSolicitacao = null;},9000);
			}
		}
	});	
}

function addAlert(despachoSolicitacao){
	
	$.gritter.add({
		// (string | mandatory) the heading of the notification
		title: despachoSolicitacao.solicitacaoCapacitacao.protocolo+ " - Solicitação de capacitação",
		// (string | mandatory) the text inside the notification
		text: despachoSolicitacao.texto,
		// (string | optional) the image to display on the left
		image: 'img/alerta_azul.png',
		// (bool | optional) if you want it to fade out on its own or just sit there
		sticky: true, 
		// (int | optional) the time you want it to be alive for before fading out (milliseconds)
		//time: 8000,
		// (string | optional) the class name you want to apply directly to the notification for custom styling
		//class_name: 'my-class',
	        // (function | optional) function called before it opens
//		before_open: function(){
//			window.setTimeout('', 3000);
//		},
		// (function | optional) function called after it opens
//		after_open: function(e){
//			alert("I am a sticky called after it opens: \nI am passed the jQuery object for the created Gritter element...\n" + e);
//		},
		// (function | optional) function called before it closes
//		before_close: function(e, manual_close){
//	                // the manual_close param determined if they closed it by clicking the "x"
//			alert("I am a sticky called before it closes: I am passed the jQuery object for the Gritter element... \n" + e);
//		},
		// (function | optional) function called after it closes
		after_close: function(){
			atualizarDespachoSolicitacao("despachosolicitacaos/receber", despachoSolicitacao);
		}
	});
}

function atualizarDespachoSolicitacao(url, object){
	$.ajax({
		"type": "PUT",
		"contentType": "application/json; charset=utf-8",
		"dataType": "json",
		"url": url,
		"beforeSend": function(xhr,settings){
			settings.data = $.toJSON(object);
		},
		"error":trataErro
	 });
	 
}
